﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace WirelessAccessPoint.Interactivity
{
    /// <summary>
    /// PasswordBoxのPasswordプロパティにバインド可能とするビヘイビアです。
    /// 
    /// 【使用方法】
    /// <i:Interaction.Behaviors>
    ///     <behavior:BindablePasswordBoxBehavior Password="{Binding Password}" />
    /// </i:Interaction.Behaviors>
    /// </summary>
    public class BindablePasswordBoxBehavior : Behavior<PasswordBox>
    {
        public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register(
            "Password",
            typeof(string),
            typeof(BindablePasswordBoxBehavior),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                PasswordPropertyChangedCallback));

        private static void PasswordPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = d as BindablePasswordBoxBehavior;
            var value = e.NewValue as string;

            if (behavior.AssociatedObject.Password != value)
            {
                behavior.AssociatedObject.Password = value;
            }
        }

        public string Password
        {
            get { return this.GetValue(PasswordProperty) as string; }
            set { this.SetValue(PasswordProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.Password = this.Password;
            this.AssociatedObject.PasswordChanged += this.PasswordChanged;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.PasswordChanged -= this.PasswordChanged;
        }

        private void PasswordChanged(object sender, RoutedEventArgs e)
        {
            var control = sender as PasswordBox;

            if (control.Password != this.Password)
            {
                this.Password = control.Password;
            }
        }
    }
}
